<?php

namespace http;

use Throwable;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

class MessageFormatter
{
    /**
     * @param RequestInterface $request
     * @param ResponseInterface|null $response
     * @param Throwable|null $error
     * @return array
     */
    public static function format(RequestInterface $request, ?ResponseInterface $response = null, Throwable $error = null): array
    {
        $array = [
            'url'       => $request->getUri()->__toString(),
            'method'    => $request->getMethod(),
            'request'   => [
                'headers'   => $request->getHeaders(),
                'data'      => $request->getBody()->__toString(),
            ],
        ];
        if ($response) {
            $array['response'] = [
                'status'    => $response->getStatusCode(),
                'headers'   => $response->getHeaders(),
                'data'      => $response->getBody()->__toString()
            ];
        }
        if ($error) {
            $array['error'] = error2array($error);
        }
        return $array;
    }
}
